package com.masterclient.app.businessmodule.usermodule.login;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eoner.baselib.fragment.FCBaseFragment;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.common.config.Config;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselibrary.utils.StringsUtils;
import com.eoner.baselib.utils.activity.UtilActivity;
import com.eoner.middlelib.eventbus.EventBusManager;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.eoner.managerlibrary.user.UserDataManager;
import com.masterclient.app.MainActivity;
import com.masterclient.app.R;
import com.masterclient.app.businessmodule.usermodule.login.dialog.InviteDialog;
import com.masterclient.app.businessmodule.usermodule.login.invite.BindInviteActivity;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.masterclient.app.businessmodule.usermodule.login.beans.AuthBindBean;
import com.masterclient.app.businessmodule.usermodule.login.beans.AuthBindData;
import com.masterclient.app.businessmodule.usermodule.login.beans.InviteInfoData;
import com.masterclient.app.businessmodule.usermodule.login.beans.InviterPopModel;
import com.masterclient.app.businessmodule.usermodule.login.beans.LoginSuccessData;
import com.masterclient.app.businessmodule.usermodule.login.contract.BindPhoneContract;
import com.masterclient.app.businessmodule.usermodule.login.contract.BindPhonePresenter;
import com.masterclient.app.businessmodule.usermodule.login.util.LoginUtil;
import com.eoner.uikit.edits.CodeEditView;
import com.masterclient.app.utils.CaptchaUtil;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @auther hjian
 * @date 2019/12/16.
 */
public class BindPhoneFragment extends FCBaseFragment<BindPhonePresenter> implements BindPhoneContract.View {


    @BindView(R.id.et_phone)
    EditText etPhone;

    @BindView(R.id.tv_verify)
    TextView tvVerify;

    @BindView(R.id.tv_code_verify)
    TextView tv_code_verify;

    @BindView(R.id.bind_phone_phonell)
    RelativeLayout bindPhonePhonell;

    @BindView(R.id.get_code_txt)
    TextView getCodeTxt;
    @BindView(R.id.codeEditView)
    CodeEditView codeEditView;
    @BindView(R.id.bind_phone_codell)
    LinearLayout bindPhoneCodell;
    @BindView(R.id.iv_check)
    ImageView ivCheck;
    @BindView(R.id.view_agreement)
    View viewAgreement;

    private boolean isSelected = false;
    private int index;
    private CaptchaUtil captchaUtil;
    private CountDownTimer timer;

    private SPUtils spUtils;
    private BindPhoneActivity activity;
    private String inviteId,shType;
    InviterPopModel inviter_pop;
    LoginSuccessData login_success_data;
    private String descs;
    private AuthBindBean.DataBean dataBean;
    private String intentSource;
    private String rewardId = "";
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(nopeAnimator != null && nopeAnimator.isRunning()){
                nopeAnimator.end();
            }
        }
    };

    @Override
    protected int requireGetLayoutId() {
        return R.layout.fragment_bind_phone;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setVisibility(View.GONE);
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {
        index = getArguments().getInt("index", 0);
        intentSource = getArguments().getString("intentSource");
        inviter_pop = (InviterPopModel) getArguments().getSerializable("inviter_pop");
        login_success_data = (LoginSuccessData) getArguments().getSerializable("login_success_data");
        if (login_success_data != null && login_success_data.getInviter_code_select_pop() != null &&
                login_success_data.getInviter_code_select_pop().bindInviterCode != null){
            rewardId = login_success_data.getInviter_code_select_pop().bindInviterCode.rewardId;
        }

        activity = (BindPhoneActivity) getActivity();

        switch (index){
            case 0:
                etPhone.setVisibility(View.VISIBLE);
                initEtHint(etPhone,"请输入手机号",15);
                bindPhonePhonell.setVisibility(View.VISIBLE);
                tvVerify.setText("下一步");
                break;
            case 1:
                bindPhoneCodell.setVisibility(View.VISIBLE);
                bindPhonePhonell.setVisibility(View.GONE);
                codeEditView.showSoftInput(null);
                getCodeTxt.setClickable(false);
                break;

        }

        spUtils = SPUtils.getInstance();
        captchaUtil = new CaptchaUtil(getContext(),"微信登录绑定手机号");

        if (index == 1) {

            timer = new CountDownTimer((60 * 1000), 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    String timeStr = "" + millisUntilFinished / 1000;
                    String temp = timeStr + " 秒后重新发送";

                    SpannableString spannableString = new SpannableString(temp);
                    spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#7399E5")), 0, timeStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#141922")), timeStr.length(), temp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    if (getCodeTxt != null && spannableString != null)
                        getCodeTxt.setText(spannableString);
                }

                @Override
                public void onFinish() {
                    getCodeTxt.setClickable(true);

                    String timeStr = "没收到验证码？";
                    String temp = timeStr + " 重新发送";

                    SpannableString spannableString = new SpannableString(temp);
                    spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#141922")), 0, timeStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#7399E5")), timeStr.length(), temp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    getCodeTxt.setText(spannableString);
                }
            };
            timer.start();
        }


        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {

                if (charSequence == null || charSequence.length() == 0) return;
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < charSequence.length(); i++) {
                    if (i != 3 && i != 8 && charSequence.charAt(i) == ' ') {
                        continue;
                    } else {
                        sb.append(charSequence.charAt(i));
                        if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != ' ') {
                            sb.insert(sb.length() - 1, ' ');
                        }
                    }
                }
                if (!sb.toString().equals(charSequence.toString())) {
                    int index = start + 1;
                    if (sb.charAt(start) == ' ') {
                        if (before == 0) {
                            index++;
                        } else {
                            index--;
                        }
                    } else {
                        if (before == 1) {
                            index--;
                        }
                    }
                    etPhone.setText(sb.toString());
                    etPhone.setSelection(index);
                }

                tvVerify.setEnabled(StringsUtils.isPhoneNum(charSequence.toString().replace(" ","")));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
//        etInvite.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                tvVerify.setEnabled(!TextUtils.isEmpty(s.toString())&&s.toString().length() == 8);
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//
//            }
//        });


        codeEditView.setOnCodeFinishListener(new CodeEditView.OnCodeFinishListener() {
            @Override
            public void onFinish(String code) {
                activity.code = code;
                tv_code_verify.setClickable(true);
                tv_code_verify.setBackgroundResource(R.drawable.login_able_click_bkg);
            }
        });

        codeEditView.setOnCodeUnFinishListener(new CodeEditView.OnCodeUnFinishListener() {
            @Override
            public void onUnFinish() {
                tv_code_verify.setClickable(false);
                tv_code_verify.setBackgroundResource(R.drawable.login_unable_click_bkg);
            }
        });
        captchaUtil.setCaptchaListerner(new CaptchaUtil.CaptchaListerner() {
            @Override
            public void onSuccess(String ne) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        baseShowCommitLoading("正在获取验证码");
                        if (getCodeTxt != null){
                            getCodeTxt.setClickable(false);
                        }
                        if (tvVerify != null)
                            tvVerify.setEnabled(false);
                    }
                });
                mPresenter.getCaptcha(activity.phone,"slogin",ne);
            }

            @Override
            public void onFailed() {
                tvVerify.setClickable(true);
                getCodeTxt.setClickable(true);

            }
        });
        if (mCommitLoading != null) {
            mCommitLoading.setCancellable(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    mPresenter.mRxManager.clear();
                    dialog.dismiss();
                }
            });
        }

        ///发送验证码
        tv_code_verify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                baseShowCommitLoading("加载中...");
                String phone = activity.phone.trim().replace(" ","");
                mPresenter.checkCaptcha(activity.code,phone,"slogin",SPUtils.getInstance().getString(Config.CUSTOMERID_TEMP),"",Config.uid,activity.union_id,activity.auth_type,activity.nick_name,activity.headimgurl);
            }
        });

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden){
            if(timer != null){
                timer.cancel();
                timer = null;
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(timer != null){
            timer.cancel();
            timer = null;
        }
    }

    @Override
    public void getCaptchaSuccess() {
        spUtils.put(Config.QUICK_VERIFY_TIME,System.currentTimeMillis());
        getCodeTxt.setClickable(true);
        tvVerify.setEnabled(true);
        baseHiddenCommitLoading();
        if (index == 0){
            activity.setCurrentPage(1,etPhone.getText().toString());
        } else {
            timer.start();
        }

    }

    @Override
    public void getCaptchaFailed(String msg) {
        showToast(msg);
        getCodeTxt.setClickable(true);
        tvVerify.setEnabled(true);
        baseHiddenCommitLoading();
    }

    //TODO:在这里判断是否需要进入邀请人页面
    @Override
    public void checkSuccess(LoginSuccessData data) {
        baseHiddenCommitLoading();
        //这里弹出pop 或者 直接登录成功
        //activity.setCurrentPage(2,"");
        if (data.isIs_show_code_select_pop() || data.isIs_show_user_info_pop()) {
            //绑定邀请人弹窗
            inviter_pop = data.getInviter_pop();
            login_success_data = data;
            login_success_data.setInviter_pop(inviter_pop);
            login_success_data.setToken(data.getToken());
            login_success_data.setCustomer_id(data.getCustomer_id());
            login_success_data.setMobile(data.getMobile());
            login_success_data.setNeed_bind_inviter(data.isNeed_bind_inviter());
            if(!TextUtils.isEmpty(data.getCustomer_id())){
                SPUtils.getInstance().put(Config.CUSTOMERID_TEMP, data.getCustomer_id());
            }
            if(!TextUtils.isEmpty(data.getToken())){
                SPUtils.getInstance().put(Config.CUSTOMER_TOKEN_TEMP, data.getToken());
            }
            if (data.getInviter_code_select_pop() != null && data.getInviter_code_select_pop().bindInviterCode != null){
                rewardId = data.getInviter_code_select_pop().bindInviterCode.rewardId;
            }

            //TODO:fix
            //绑定邀请人弹窗
            Intent intent = new Intent(getActivity(), BindInviteActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("auth_type", activity.auth_type);
            bundle.putString("phone", activity.phone);
            bundle.putString("union_id", activity.union_id);
            bundle.putString("nick_name", activity.nick_name);
            bundle.putString("headimgurl", activity.headimgurl);
            bundle.putSerializable("inviter_pop", data.getInviter_pop());
            bundle.putSerializable("lg_data",data);
            intent.putExtras(bundle);
            getActivity().startActivityForResult(intent, BindInviteActivity.REQUEST_CODE);

        }else {
            //已绑定
            showToast("登录成功");
            SPUtils.getInstance().put(Config.CUSTOMERID, data.getCustomer_id());
            SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, data.getToken());
            UserDataManager.getInstance().updateUserStatus(data.isIs_disable());
            EventBusManager.post(EventBusManager.createLoginSuccessEvent());
            EventBusManager.post(EventBusManager.createHomeRefreshEvent());
            activity.setResult(activity.BIND_SUCCESS);
            activity.finish();
            if (!UtilActivity.isCurActivity("MainActivity")) {
                startActivitryWithBundle(MainActivity.class, null);
            }
        }
    }

    @Override
    public void checkFailded(String msg, String failReason) {
        showToast(msg);
        baseHiddenCommitLoading();
    }

    @Override
    public void authBindSuccess(String code,AuthBindData data,String msg,String inviteCode) {
        UserDataManager.getInstance().updateInviteCode(inviteCode);
        if ("30000".equals(code)){
            rewardId = data.getInviteInfo().getReward_id();
            dialog.refreshInviteInfo(data.getInviteInfo(),data.getNotice());
        }else {
            if(dialog != null){
                dialog.dismiss();
            }
            if (data != null) {
                if(!TextUtils.isEmpty(data.getCustomer_id())){
                    SPUtils.getInstance().put(Config.CUSTOMERID, data.getCustomer_id());
                }else {
                    SPUtils.getInstance().put(Config.CUSTOMERID, SPUtils.getInstance().getString(Config.CUSTOMERID_TEMP));
                }
                if(!TextUtils.isEmpty(data.getToken())){
                    SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, data.getToken());
                }else{
                    SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN_TEMP));
                }
            }
            EventBusManager.post(EventBusManager.createLoginSuccessEvent());
            EventBusManager.post(EventBusManager.createHomeRefreshEvent());

            activity.setResult(activity.BIND_SUCCESS);
            activity.finish();
            if (!UtilActivity.isCurActivity("MainActivity")) {
                startActivitryWithBundle(MainActivity.class, null);
            }
        }
        baseHiddenCommitLoading();
        showToast(msg);
    }

    @Override
    public void authBindFailded(String msg) {
        baseHiddenCommitLoading();
        showToast(msg);
    }

    @Override
    public void showInviteInfo(InviteInfoData inviteInfoData) {
        inviteId = inviteInfoData.getInvite_id();
        rewardId = "";
        dialog.refreshInviteInfo(inviteInfoData,"");
    }

    @Override
    public void showInviteInfoFail(String msg) {
        dialog.refreshErrorInfo(msg);
    }

    @OnClick({R.id.tv_verify,R.id.get_code_txt,R.id.tv_agreement,
            R.id.iv_check_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_verify:
                if (!isSelected){
                    startLeftAndRightShake();
                    mHandler.sendEmptyMessageDelayed(0,500);
                    ToastUtil.showToast("请先同意《用户服务协议》");
                    return;
                }

                if (index == 0) {
                    String phone = etPhone.getText().toString().trim().replace(" ","");
                    if(StringsUtils.isPhoneNum(phone)){
                        activity.phone = phone;
                        if(SystemConfigStorage.getInstance().isOpenSlipPageCode()) {
                            if (CaptchaUtil.CAPTCHA_NUMBER_TIMES >= Config.CAPTCHA_MAX_TIMES){
                                mPresenter.getCaptcha(phone,"slogin","");
                            }else {
                                captchaUtil.start();
                            }
                        }else {
                            baseShowCommitLoading("正在获取验证码");
                            mPresenter.getCaptcha(phone,"slogin","");
                            tvVerify.setEnabled(false);
                        }
                    }else {
                        showToast("请输入正确的手机号");
                    }
                }
                break;
            case R.id.get_code_txt:
                if(SystemConfigStorage.getInstance().isOpenSlipPageCode()) {
                    if (CaptchaUtil.CAPTCHA_NUMBER_TIMES >= Config.CAPTCHA_MAX_TIMES){
                        mPresenter.getCaptcha(activity.phone,"slogin","");
                    }else {
                        captchaUtil.start();
                    }
                }else {
                    mPresenter.getCaptcha(activity.phone,"slogin","");
                    getCodeTxt.setClickable(false);
                }
                break;
            case R.id.tv_agreement:
                startActivitryWithBundle(BridgeActivity.class, new String[][]{{"url", SystemConfigStorage.getInstance().getServiceRuleUrl()}, {"title", "中华大师汇服务协议"}});
                break;

            case R.id.iv_check_btn:
                if (isSelected){
                    isSelected = false;
                    ivCheck.setImageResource(R.mipmap.icon_lg_no_sel);
                }else {
                    isSelected = true;
                    ivCheck.setImageResource(R.mipmap.icon_lg_sel);
                }
                break;

        }
    }

    ObjectAnimator nopeAnimator;
    private void startLeftAndRightShake() {
        //左右移动
        nopeAnimator = LoginUtil.nope(viewAgreement);
        nopeAnimator.setRepeatCount(ValueAnimator.INFINITE);
        nopeAnimator.start();
    }

    private InviteDialog dialog;
    private void show_pop_dialog(LoginSuccessData data) {
        if (dialog == null) {
            dialog = new InviteDialog(getActivity(), new InviteDialog.OnChooseListener() {
                @Override
                public void cancel() {
                    dialog.dismiss();
                }

                @Override
                public void getByInviteCode(String invite_code) {
                    mPresenter.getInviteInfo(invite_code);
                }

                @Override
                public void confirm(String inviteCode) {
                    //dialog.dismiss();
                    baseShowCommitLoading("登录中");
                    mPresenter.authBind(activity.auth_type,activity.phone, activity.union_id,
                            inviteCode,Config.uid,activity.nick_name,activity.headimgurl,data.getNonce(),
                            SPUtils.getInstance().getString(Config.CUSTOMERID_TEMP),rewardId);

                }

                @Override
                public void skip_login() {
                    if(login_success_data == null){
                        return;
                    }
                    showToast("登录成功");
                    SPUtils.getInstance().put(Config.CUSTOMERID, login_success_data.getCustomer_id());
                    SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, login_success_data.getToken());
                    UserDataManager.getInstance().updateUserStatus(login_success_data.isIs_disable());
                    EventBusManager.post(EventBusManager.createLoginSuccessEvent());
                    EventBusManager.post(EventBusManager.createHomeRefreshEvent());
                    setResult();
                    getActivity().finish();
                    if (!UtilActivity.isCurActivity("MainActivity")) {
                        startActivitryWithBundle(MainActivity.class, null);
                    }
                }
            });
        }
        dialog.show();
        dialog.setData(data);
    }

    private void setResult() {
        if(getActivity().getIntent()!=null&&getActivity().getIntent().getExtras() != null){
            Bundle bundle = getActivity().getIntent().getExtras();
            String result = bundle.getString("result_code");
            if(!TextUtils.isEmpty(result)){
                getActivity().setResult(Integer.valueOf(result));
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(timer != null){
            timer.cancel();
            timer = null;
        }
    }

}
